#ifndef F_CPU
#define F_CPU 1000000UL
#endif

#include "serial.h"

#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include <string.h>
#include <stdio.h>

volatile char msg_rx[SERIAL_BUF_SIZE];
volatile char msg_tx[SERIAL_BUF_SIZE];
volatile uint8_t rx_buf_pos;
volatile uint8_t tx_buf_pos;
volatile uint8_t serial_rx;

ISR(USART_RXC_vect) {

  char rx_char = UDR;

  if (rx_char=='\n') {
    msg_rx[rx_buf_pos++] = rx_char;
    msg_rx[rx_buf_pos++] = '\0';
    if (serial_rx==0) serial_rx = 1;
  } 
  else {
    msg_rx[rx_buf_pos++] = rx_char;
  }
  
  if (rx_buf_pos==SERIAL_BUF_SIZE-1) rx_buf_pos=0;
}

/* ISR(USART_UDRE_vect) { */
/*   if (msg_tx[tx_buf_pos] != '\0') { */
/*     UDR = msg_tx[tx_buf_pos++]; */
/*   } */
/*   else { */
/*     UCSRB &= ~(1 << UDRIE); */
/*     tx_buf_pos = 0; */
/*   } */
/* } */

void serial_init(unsigned int bittimer)
{
  /* Set the baud rate */
  UBRRH = (unsigned char) (bittimer >> 8);
  UBRRL = (unsigned char) bittimer;
  /* Set the framing to 8N1 */
  UCSRC = (3 << UCSZ0);
  /* Enable RX Interrupt and Engage!*/ 
  UCSRB = (1 << RXCIE) | (1 << RXEN) | (1 << TXEN);
  /* Initialize Serial Receiver Variables */
  serial_rx = 0;
  tx_buf_pos = 0;
  rx_buf_pos = 0;
}

/* void serial_transmit(char* msg) */
/* { */
/*   strcpy((char*) msg_tx,msg); */
/*   tx_buf_pos = 0; */
/*   UCSRB |= (1 << UDRIE); */
/* } */

void serial_transmit(char data)
{
  /* Wait for empty transmit buffer */
  while ( !( UCSRA & (1<<UDRE)) );
  /* Put data into buffer, sends the data */
  UDR = data;

}

void serial_read_buffer(char *msg_var)
{

  serial_rx = 0;
  rx_buf_pos = 0;
  strcpy(msg_var,(char*) msg_rx);

}
